package com.atguigu.eud_teacher.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.commonutils.exceptionhandler.GuliException;
import com.atguigu.eud_teacher.dao.SubjectDao;
import com.atguigu.eud_teacher.entity.SubjectEntity;
import com.atguigu.eud_teacher.entity.excle.SubjectData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.val;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;

@AllArgsConstructor
@NoArgsConstructor
public class SubjectExecleListener extends AnalysisEventListener<SubjectData> {
    private SubjectDao baseMapper;

    /**
     * 遍历每一行数据
     *
     * @param subjectData
     * @param analysisContext
     */
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new GuliException(20001, "表格为空");
        }
        SubjectEntity existOneEntity = this.existOneSubject(subjectData.getLevelOneTitle());
        if (existOneEntity == null) {
            existOneEntity = new SubjectEntity();
            QueryWrapper<SubjectEntity> wrapper = new QueryWrapper<>();
            //根据pid插入一级
            existOneEntity.setParentId("0");
            existOneEntity.setTitle(subjectData.getLevelOneTitle());
            baseMapper.insert(existOneEntity);
        }
        String pid = existOneEntity.getId();
        SubjectEntity existTwoEntity = this.existTwoSubject(subjectData.getLevelTwoTitle(), pid);
        if (existTwoEntity == null) {
            existTwoEntity = new SubjectEntity();
            QueryWrapper<SubjectEntity> wrapper = new QueryWrapper<>();
            //根据pid插入一级
            existTwoEntity.setParentId(pid);
            existTwoEntity.setTitle(subjectData.getLevelTwoTitle());
            baseMapper.insert(existTwoEntity);
        }
    }

    //判断一级分类不能重复添加
    private SubjectEntity existOneSubject(String title) {
        QueryWrapper<SubjectEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("title", title);
        wrapper.eq("parent_id", "0");
        SubjectEntity oneSubject = baseMapper.selectOne(wrapper);
        return oneSubject;
    }

    //判断二级分类不能重复添加

    private SubjectEntity existTwoSubject(String title, String pid) {
        QueryWrapper<SubjectEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("title", title);
        wrapper.eq("parent_id", pid);
        SubjectEntity twoSubject = baseMapper.selectOne(wrapper);
        return twoSubject;
    }


    /**
     * 收尾数据
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("解析完成");
    }


}
